package com.oro.validator;

import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class UrlValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		String enteredValue = (String) value;

		Pattern p0 = Pattern
				.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"); // Works
		Pattern p1 = Pattern
				.compile("^(?:([^:/?#]+):)?(?://((?:(([^:@]*):?([^:@]*))?@)?([^:/?#]*)(?::(\\d*))?))?((((?:[^?#/]*/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)");
		Pattern p2 = Pattern
				.compile("^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?://)?((?:(([^:@]*):?([^:@]*))?@)?([^:/?#]*)(?::(\\d*))?)(((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[?#]|$)))*/?)?([^?#/]*))(?:\\?([^#]*))?(?:#(.*))?)");
		Pattern p4 = Pattern.compile("[0-9]+");

		Matcher m = p0.matcher(enteredValue);

		if (!m.matches()) {

			String baseName = context.getApplication().getMessageBundle();
			Locale currentLocale = context.getViewRoot().getLocale();
			ResourceBundle rb = ResourceBundle.getBundle(baseName,
					currentLocale);

			FacesMessage message = new FacesMessage();
			message.setSummary(rb.getString("invalid_url"));
			message.setDetail(rb.getString("invalid_url_detail"));

			throw new ValidatorException(message);
		}

	}
}
